import qs from 'qs'
import store from "@/store";
import api from "@/api";

/**
 * @description 翻译
 * */
function translate(text, source, target) {
	if (!text) return;
	if (store.getters.translate === 'google') { // 谷歌翻译
		return new Promise((resolve) => {
			uni.request({
				method: "get",
				url: 'https://translate.googleapis.com/translate_a/single',
				data: {
					client: 'gtx',
					dt: 't',
					sl: source,
					tl: target,
					q: text
				},
				success: result => resolve(result.data[0][0][0]),
				fail: () => { // 谷歌翻译失败转阿里翻译
					store.dispatch('setTranslate', 'alibaba');
					let param = {
						text,
						source,
						target
					}
					api.translateApi(param)
						.then(result => {
							let response = JSON.parse(result.resultParam.translate);
							resolve(response.translated)
						})
						.catch(() => {
							resolve('')
						})
				}
			})
		});
	} else { // 阿里翻译
		return new Promise((resolve) => {
			let param = {
				text,
				source,
				target
			}
			api.translateApi(param)
				.then(result => {
					let response = JSON.parse(result.resultParam.translate);
					resolve(response.translated)
				})
				.catch(() => {
					resolve('')
				})
		})
	}
}

// 中文 -> 英文
export function translateZhToEn(text) {
	return translate(text, 'zh', 'en')
}

// 中文 -> 老挝
export function translateZhToLaos(text) {
	return translate(text, 'zh', 'lo')
}

// 老挝 -> 中文
export function translateLaosToZh(text) {
	return translate(text, 'lo', 'zh')
}

// 老挝 -> 英文
export function translateLaosToEn(text) {
	return translate(text, 'lo', 'en')
}
